<?php
/** Yz_SQL_Statement
*
*/

class Yz_SQL_Join
    extends Yz_Class
{

    protected $table;
    protected $type;
    protected $alias;
    protected $conditions;

    protected function __construct($type, $table, $alias)
    {
        $this->type  = $type;
        $this->table = $table;
        $this->alias = $alias;
    }

    public static function leftJoin($table, $alias=null)
    {
        return new static('LEFT JOIN', $table, $alias);
    }

    public static function commaJoin($table, $alias=null)
    {
        return new static(',', $table, $alias);
    }

    public function setAliasIfEmpty($alias)
    {
        if (null === $this->alias)
        {
            $alias = Yz_String::testNotEmpty($alias);
        }
        return $this;
    }


    public function joinOn($conds)
    {
        if (is_scalar($conds)) {
            $conds = Yz_String::testNotEmpty($conds);
        } else {
            $list = new Yz_Array($conds);
            if ($list->isEmpty()) {
                throw new Yz_Exception("Empty conditions");
            }
            $conds = $list->join(" AND ");
        }
        $this->conditions = "ON " . $conds;
        return $this;
    }

    public function joinUsing($fields)
    {
        $fields = Yz_String::testNotEmpty($fields);
        $this->conditions = "USING({$fields})";
        return $this;
    }

    public function getClause()
    {
        $type = $this->type;
        if (null === $type) {
            throw new Yz_Exception("Join clause not complete");
        }
        if ("," === $type) {
            return ",\n  {$this->table} {$this->alias}";
        } else {
            return "\n{$type} {$this->table} {$this->alias} {$this->conditions}";
        }
    }

} // class

